package com.jcooky.tutorfs.proxy.processor;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcooky.tutorfs.proxy.Attributes;
import com.jcooky.tutorfs.proxy.filesystem.AbstractFileSystem;
import com.jcooky.tutorfs.proxy.filesystem.FileSystemException;
import com.jcooky.tutorfs.proxy.protocol.AbstractMessage;
import com.jcooky.tutorfs.proxy.protocol.ReqWrite;
import com.jcooky.tutorfs.proxy.protocol.ResOk;

public class ReqWriteProcessor implements MessageProcessor<ReqWrite> {
	private static final Logger logger = LoggerFactory.getLogger(ReqWriteProcessor.class);
	
	public void process(IoSession session, ReqWrite message) throws ProcessException {
		logger.info("BEGIN - ReqWrite processing");
		AbstractFileSystem fs = (AbstractFileSystem)session.getAttribute(Attributes.FILE_SYSTEM);
		ResOk resOk = (ResOk)AbstractMessage.getMessage(AbstractMessage.TYPE_RES_OK);
		IoBuffer sendBuffer = IoBuffer.allocate(resOk.length(), true);
		try {
			fs.write(message.getFilepath(), message.getData(), message.getPos(), message.getSize());
			resOk.setOk(true);
		} catch(FileSystemException e) {
			resOk.setOk(false);
			throw new ProcessException(e);
		} finally {
			sendBuffer.clear();
			resOk.toBytes(sendBuffer);
			sendBuffer.flip();
			session.write(sendBuffer);
		}
		
		logger.info("  END - ReqWrite processing");
	}
}
